package com.course.server.service;

import com.course.server.domain.Course;
import com.course.server.domain.CourseExample;
import com.course.server.dto.CourseDTO;
import com.course.server.dto.PageDTO;
import com.course.server.mapper.CourseMapper;
import com.course.server.util.CopyUtil;
import com.course.server.util.UuidUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class CourseService {

    @Resource
    private CourseMapper courseMapper;

    public void list(PageDTO pageDTO){

        PageHelper.startPage(pageDTO.getPage(), pageDTO.getSize());
        //分页规则：调用startPage方法后，下面遇到的第一条select语句会进行分页
        CourseExample courseExample = new CourseExample();

        courseExample.setOrderByClause("sort asc");

        List<Course> courses = courseMapper.selectByExample(courseExample);

        PageInfo<Course> pageInfo = new PageInfo<>(courses);

        pageDTO.setTotal(pageInfo.getTotal());

        ArrayList<CourseDTO> courseDTOList = new ArrayList<>();

        for (int i = 0; i < courses.size(); i++) {
            Course course = courses.get(i);
            CourseDTO courseDTO = new CourseDTO();
            BeanUtils.copyProperties(course, courseDTO);
            courseDTOList.add(courseDTO);
        }
        pageDTO.setList(courseDTOList);
    }

    public void save(CourseDTO courseDTO){
        Course course = CopyUtil.copy(courseDTO, Course.class);
        if (StringUtils.isEmpty(courseDTO.getId())){
            //前端没有带过来id，则是新增
            this.insert(course);
        }else{
            this.update(course);
        }
    }

    private void insert(Course course){
        Date now = new Date();
        course.setCreatedAt(now);
        course.setUpdatedAt(now);
        course.setId(UuidUtil.getShortUuid());
        courseMapper.insert(course);
    }

    private void update(Course course){
        Date now = new Date();
        course.setUpdatedAt(now);
        courseMapper.updateByPrimaryKey(course);
    }

    public void delete(String id){
        courseMapper.deleteByPrimaryKey(id);
    }


}
